# CMake 脚本：修改 cmake_install.cmake，在开头插入版本检查和卸载代码
# 此脚本在构建时执行，修改生成的 cmake_install.cmake 文件

# 从命令行参数获取构建目录
if(NOT DEFINED CMAKE_CURRENT_BINARY_DIR)
    message(FATAL_ERROR "CMAKE_CURRENT_BINARY_DIR 未定义")
endif()

set(CMAKE_INSTALL_FILE "${CMAKE_CURRENT_BINARY_DIR}/cmake_install.cmake")
set(UNINSTALL_SCRIPT "${CMAKE_CURRENT_BINARY_DIR}/CheckAndUninstall.cmake")

# 检查 cmake_install.cmake 是否存在
if(NOT EXISTS "${CMAKE_INSTALL_FILE}")
    message(WARNING "cmake_install.cmake 文件不存在，跳过修改")
    return()
endif()

# 读取 cmake_install.cmake 内容
file(READ "${CMAKE_INSTALL_FILE}" CMAKE_INSTALL_CONTENT)

# 检查是否已经插入过卸载代码
string(FIND "${CMAKE_INSTALL_CONTENT}" "# 安装前版本检查和卸载" FOUND)
if(NOT FOUND EQUAL -1)
    message(STATUS "cmake_install.cmake 已经包含卸载代码，跳过修改")
    return()
endif()

# 构建要插入的卸载代码
set(UNINSTALL_CODE "# 安装前版本检查和卸载
message(STATUS \"执行安装前版本检查和卸载...\")
execute_process(
    COMMAND \"${CMAKE_COMMAND}\" -P \"${UNINSTALL_SCRIPT}\"
    RESULT_VARIABLE UNINSTALL_RESULT
)
if(NOT UNINSTALL_RESULT EQUAL 0)
    message(WARNING \"版本检查和卸载过程可能有问题，但继续安装...\")
endif()

")

# 在文件开头插入卸载代码
set(CMAKE_INSTALL_CONTENT "${UNINSTALL_CODE}${CMAKE_INSTALL_CONTENT}")

# 写回文件
file(WRITE "${CMAKE_INSTALL_FILE}" "${CMAKE_INSTALL_CONTENT}")
message(STATUS "已修改 cmake_install.cmake，在安装前插入版本检查和卸载代码")

